#!/usr/bin/perl 

use strict;
use warnings;

use IO::Socket;
use Net::hostent;
use Switch;
use threads;

my $port = shift || 1163;
my $server = IO::Socket::INET->new( Proto => 'tcp',
                                    LocalPort => $port,
                                    Listen => SOMAXCONN,
                                    Reuse => 1) || die "can't setup server";
print "[Server $0 is running]\n";

while ( my $client = $server->accept() ) {
  threads->create( \&listener, $client )->detach;
}

sub listener {
  my $client = shift;
  while ( 'TRUE' ) {
    $client->autoflush(1);
    print $client "Welcome to $0\n type help to get a list of commands.\n";
    my $hostinfo = gethostbyaddr($client->peeraddr);
    
    #print this informations on the server side
    printf "[Connect from %s]\n", $hostinfo->name || $client->peerhost;
    
    print $client "[server]\$";
    while ( <$client>) {
      next unless /\S/;
      switch ( $_ ) {
        case  m/quit|exit/i  { return close $client; }
        case  m/date|time/i  { printf $client "%s\n", scalar localtime; }
        case  m/services/i   { print $client `cat /etc/services 2>&1`; }
        case  m/.*/          { print $client "Commands: quit date services\n"; }
      }
      print $client "[server]\$ ";
    }
  }
}
